package com.service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.dao.IRetCrtNoDao;
import com.dao.IRetWODao;
import com.icim.service.ICIMBaseService;
import com.model.Ret_crt_no;
import com.model.Ret_crt_noId;
import com.model.Ret_wo;
import com.tx.Xpcrtno.XpcrtnoI;
import com.tx.Xpcrtno.XpcrtnoO;
import com.util.GUIDGenerator;
import com.util.MqOpe;
import com.util.Util;

import static com.def.GenericDef.*;

@Scope("prototype")
@Service("XpcrtnoService")
public class XpcrtnoService extends ICIMBaseService{
	
	
	private static Logger logger = Logger.getLogger(XpcrtnoService.class);
	private XpcrtnoI inTrx;
	private XpcrtnoO outTrx;

	@Autowired
	private IRetCrtNoDao retCrtNoDao;

	@Autowired
	private IRetWODao retWODao;
	
	public String subMainProc(String strInMsg) {
		inTrx = new XpcrtnoI();
		outTrx = new XpcrtnoO();
		outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));
		char actionFlg;
		String outMsg;
		MqOpe mqOpe = new MqOpe();

		try {
			inTrx = (XpcrtnoI) mqOpe.inStr2Obj(strInMsg, inTrx);
			logger.info("InTrx is " + strInMsg);

			actionFlg = inTrx.getAction_flg().charAt(0);

			switch (actionFlg) {
			case 'Q': {
				getSerialNO();
				break;
			}
			case 'U': {
				updateSerialNO();
				break;
			}
			case 'B': {
				autoCreatBox();
				break;
			}
			case 'L': {
				autoCreatLot();
				break;
			}
			case 'P':{
				autoCreateDpsPlan();
				break;
			}
			case 'O':{
				oncellserial();
				break;
			}
			case 'N':{
				autoDn();
				break;
			}
			case 'A':{
				autoCreatPallet();
				break;
			}
			case '7':{// for 007客户生成栈板号
				autoCreatPalletFor007();
				break;
			}
			case '3':{// for 003客户生成栈板号
				autoCreatPallet003();
				break;
			}
			case 'C':{// 二维码流水码
				autoCreatStrForQR();
				break;
			}
			default: {
				outTrx.setRtn_mesg("Invalide type input: [" + actionFlg + "]");
				outTrx.setRtn_code(E_XPINQBOX_INVALID_INPUT + "");
			}
			}
			if ((RETURN_CODE_OK).equals(outTrx.getRtn_code())) {
				retCrtNoDao.flushCurSession();
			} else {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}

		} catch (Exception ex) {
			outTrx.setRtn_mesg(ex.toString());
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			logger.error(Util.stackTraceToString(ex));
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		} finally {
			outMsg = mqOpe.obj2Str(outTrx);
		}
		return outMsg;
	}

	private String getNextSeq(Ret_crt_no ret_crt_no) {
		int iSerial = 0;
		if (ret_crt_no != null) {
			iSerial = Integer.valueOf(ret_crt_no.getSerial_no());
		}
		iSerial++;
		DecimalFormat df_X = new DecimalFormat("00");
		return df_X.format(iSerial);
	}
	private void autoCreateDpsPlan() {

		String key_id = inTrx.getKey_id();
		String type = inTrx.getType();
		String secialNO = "";
		Ret_crt_noId id = new Ret_crt_noId();
		id.setKey_id(key_id);
		id.setType(type);
		Ret_crt_no ret_crt_no = retCrtNoDao.get(id);
		
		secialNO = getNextSeq(ret_crt_no);
		if(ret_crt_no==null){
			ret_crt_no = new Ret_crt_no();
			ret_crt_no.setId(id);
		}
		ret_crt_no.setSerial_no(secialNO);
		retCrtNoDao.saveOrUpdate(ret_crt_no);
		
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		outTrx.setSerial_no(key_id + secialNO);
	}

	private void getSerialNO() {
		String type = inTrx.getType();
		
		switch (type.charAt(0)) {
		case CHAR_SERIAL_TYPE_SO: {
			getWoSerialNoFnc();
			break;
		}
		default:
			//
		}

	}

	private String getYear(){
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		return String.valueOf(year);
	}
	private String getWoSerialNoFnc() {
		
		int iSerial = 0;
		
		String key_id = inTrx.getKey_id();
		Ret_crt_noId id = new Ret_crt_noId();
		String year = getYear();
		id.setKey_id(year);
		id.setType(STRING_SERIAL_TYPE_SO);
		Ret_crt_no ret_crt_no = retCrtNoDao.get(id);
		
		if (ret_crt_no == null) {
			logger.warn("Ret_crt_no 表中key_id='"+year+"'type='"+STRING_SERIAL_TYPE_SO+"'没找到，已经自动开始创建");
			Ret_crt_no crt_no = new Ret_crt_no();
			
			crt_no.setId(id);
			crt_no.setUnq_seq_id(GUIDGenerator.javaGUID());
			crt_no.setSerial_no("001");
			
			retCrtNoDao.save(crt_no);
			ret_crt_no = crt_no;
			logger.warn("Ret_crt_no 表中key_id='"+year+"'type='"+STRING_SERIAL_TYPE_SO+"'自动创建成功");
		}
		
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		outTrx.setKey_id(key_id);
		
		String serialNo = "";
		String woId="";
		if (ret_crt_no != null) {
			iSerial = Integer.valueOf(ret_crt_no.getSerial_no());
		}
		while(true){
			iSerial++;
			serialNo = Util.comInt2String(iSerial, 4);
			woId = "DQR"+ret_crt_no.getId().getKey_id()+serialNo;
			if(retWODao.get(woId)==null){
				break;
			}
		}
		outTrx.setSerial_no(woId);
		return serialNo;
	}
	private void updateSerialNO() {
		String key_id = inTrx.getKey_id();
		String type = inTrx.getType();
		String secialNO = inTrx.getSerial_no();
		String woId="";
		Ret_crt_noId id = new Ret_crt_noId();
		String year = getYear();
		id.setKey_id(year);
		id.setType(type);
		Ret_crt_no ret_crt_no = retCrtNoDao.get(id);
		
		switch (type.charAt(0)) {
		case CHAR_SERIAL_TYPE_SO: {
				if(ret_crt_no==null){
					ret_crt_no = new Ret_crt_no();
					ret_crt_no.setId(id);
				}
				ret_crt_no.setSerial_no(secialNO);
			
			retCrtNoDao.saveOrUpdate(ret_crt_no);
			
			outTrx.setRtn_code(RETURN_CODE_OK);
			outTrx.setRtn_mesg(RETURN_MESG_OK);
			outTrx.setKey_id(key_id);
			outTrx.setSerial_no(woId);
			break;
		}
		default:
			//
		}
	}
	private String getBoxSerialNoFnc(Ret_crt_no ret_crt_no) {
		int iSerial = 0;
		if (ret_crt_no != null) {
			iSerial = Integer.valueOf(ret_crt_no.getSerial_no());
		}
		iSerial++;
		DecimalFormat df_X = new DecimalFormat("000");
		//return Util.comInt2String(iSerial, 3);
		return df_X.format(iSerial);
	}
	
	private void autoCreatBox() {
		String key_id = inTrx.getKey_id();
		String type = inTrx.getType();
		String secialNO = "";
		Ret_crt_noId id = new Ret_crt_noId();
		id.setKey_id(key_id);
		id.setType(type);
		Ret_crt_no ret_crt_no = retCrtNoDao.get(id);
		
		secialNO = getBoxSerialNoFnc(ret_crt_no);
		if(ret_crt_no==null){
			ret_crt_no = new Ret_crt_no();
			ret_crt_no.setId(id);
		}
		ret_crt_no.setSerial_no(secialNO);
		retCrtNoDao.saveOrUpdate(ret_crt_no);
		
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		outTrx.setSerial_no(key_id + secialNO);
	}
	
	private void autoCreatLot() {
		int iSerial = 0;
		String key_id = inTrx.getKey_id();
		String type = inTrx.getType();
		String secialNO = "";
		Ret_crt_noId id = new Ret_crt_noId();
		id.setKey_id(key_id);
		id.setType(type);
		Ret_crt_no ret_crt_no = retCrtNoDao.get(id);
		if(ret_crt_no==null){
			ret_crt_no = new Ret_crt_no();
			ret_crt_no.setId(id);
		}else{
			iSerial = Integer.valueOf(ret_crt_no.getSerial_no());
		}
		iSerial++;
		if(iSerial > 999){
			outTrx.setRtn_code(E_XPCRTNO_MAX_SERIAL_NO + "");
			outTrx.setRtn_mesg("批次自动生成的最大流水码为999！");
		}else{
			if(STRING_SERIAL_TYPE_LOT.equals(type)){//流水3码
				secialNO = Util.comInt2String(iSerial, 3);
			}else if(STRING_SERIAL_TYPE_WO.equals(type)){
				secialNO = Util.comInt2String(iSerial, 4);
			}
			ret_crt_no.setSerial_no(secialNO);
			retCrtNoDao.saveOrUpdate(ret_crt_no);
			outTrx.setRtn_code(RETURN_CODE_OK);
			outTrx.setRtn_mesg(RETURN_MESG_OK);
			outTrx.setSerial_no(secialNO);
		}
	}
	
	/**
	 * 5400:自动生成交货订单号
	 * 生成规则：年月日+三位流水码
	 * 每天第一次insert，删除之前type='N' and key_id != ?
	 * auth：thy
	 */
	private void autoDn(){
		String key_id = Util.getEvtTimeforVer();
		String type = inTrx.getType();
		
		Ret_crt_noId id = new Ret_crt_noId();
		id.setKey_id(key_id);
		id.setType(type);
		Ret_crt_no ret_crt_no = retCrtNoDao.get(id);
		if (null == ret_crt_no) {
			outTrx.setRtn_code(RETURN_CODE_OK);
			outTrx.setRtn_mesg(RETURN_MESG_OK);
			outTrx.setSerial_no(key_id+"001");
			Ret_crt_no ret_crt_no2 = new Ret_crt_no();
			ret_crt_no2.setId(id);
			ret_crt_no2.setSerial_no("001");
			retCrtNoDao.save(ret_crt_no2);
			
			String sql = "FROM Ret_crt_no WHERE type='"+type+
						"' AND key_id != '"+key_id+"'";
			List<Ret_crt_no> retCrtNoList = new ArrayList<Ret_crt_no>();
			retCrtNoList = retCrtNoDao.find(sql);
			if (!retCrtNoList.isEmpty()) {
				retCrtNoDao.deleteAll(retCrtNoList);
			}
		}else {
			String serial_no = ret_crt_no.getSerial_no();
			int num = Integer.valueOf(serial_no)+1;
			
			if(num > 999){
				outTrx.setRtn_code(E_XPCRTNO_MAX_SERIAL_NO + "");
				outTrx.setRtn_mesg("自动生成的最大流水码为999！");
			}else {
				String rtnStr = key_id+Util.comInt2String(num, 3);
				outTrx.setRtn_code(RETURN_CODE_OK);
				outTrx.setRtn_mesg(RETURN_MESG_OK);
				outTrx.setSerial_no(rtnStr);
				
				ret_crt_no.setSerial_no(Util.comInt2String(num, 3));
				retCrtNoDao.update(ret_crt_no);
			}
		}
	}
	
	private void oncellserial() {
		int iSerial = 0;
		String key_id = inTrx.getKey_id();
        String t = "";
		String key = "";
		String keytime = "";
		if(key_id.substring(11, 12).equals("0")){
		   t = key_id.substring(12, 13);
		}else{
		   t = key_id.substring(11, 13);	
		}
		if(Integer.parseInt(t)>=8){
			keytime = key_id;
		}else{
		    keytime = Util.getYesterData(key_id);
			
		}
		String y = keytime.substring(2,4);
		String m = keytime.substring(5, 7);
		String d = keytime.substring(8, 10);
		key = y + m + d;
		String type = inTrx.getType();
		String secialNO = "";
		Ret_crt_noId id = new Ret_crt_noId();
		id.setKey_id(key);
		id.setType(type);
		Ret_crt_no ret_crt_no = retCrtNoDao.get(id);
		if(ret_crt_no==null){
            Ret_crt_no crt_no = new Ret_crt_no();  
            crt_no.setId(id);
			crt_no.setUnq_seq_id(GUIDGenerator.javaGUID());
			crt_no.setSerial_no("01");
			retCrtNoDao.save(crt_no);
			outTrx.setRtn_code(RETURN_CODE_OK);
			outTrx.setRtn_mesg(RETURN_MESG_OK);
			outTrx.setSerial_no("01");
        }else{
		iSerial = Integer.valueOf(ret_crt_no.getSerial_no());
		iSerial++;
		secialNO = Util.comInt2String(iSerial, 2);
		ret_crt_no.setSerial_no(secialNO);
		retCrtNoDao.saveOrUpdate(ret_crt_no);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		outTrx.setSerial_no(secialNO);
	   }
	}
	
	//pallet
	private void autoCreatPallet() {
		int iSerial = 0;
		String key_id = inTrx.getKey_id();
		String type = inTrx.getType();
		String secialNO = "";
		Ret_crt_noId id = new Ret_crt_noId();
		id.setKey_id(key_id);
		id.setType(type);
		Ret_crt_no ret_crt_no = retCrtNoDao.get(id);
		if(ret_crt_no==null){
			ret_crt_no = new Ret_crt_no();
			ret_crt_no.setId(id);
		}else{
			iSerial = Integer.valueOf(ret_crt_no.getSerial_no());
		}
		iSerial++;
		if(iSerial > 9999){
			outTrx.setRtn_code(E_XPCRTNO_MAX_SERIAL_NO + "");
			outTrx.setRtn_mesg("批次自动生成的最大流水码为9999！");
		}else{
			secialNO = Util.comInt2String(iSerial, 4);
			ret_crt_no.setSerial_no(secialNO);
			retCrtNoDao.saveOrUpdate(ret_crt_no);		
			outTrx.setRtn_code(RETURN_CODE_OK);
			outTrx.setRtn_mesg(RETURN_MESG_OK);
			outTrx.setSerial_no(secialNO);
		}
	}
	
	/**
	 * 007栈板号自动生成
	 */
	private void autoCreatPalletFor007(){
		int iSerial = 0;
		Ret_crt_noId id = new Ret_crt_noId();
		//第1、2码为固定WA
		String pallet_id = "WA";
		//第3、4码为WO的product ID的末两位
		Ret_wo ret_wo = retWODao.get(inTrx.getWo_id());
		if(ret_wo == null){
			outTrx.setRtn_code(E_RET_WO + E_READ_NOT_FOUND + "");
			outTrx.setRtn_mesg("找不到客户代码[" + inTrx.getWo_id() + "]的信息！");
		}
		pallet_id = pallet_id + ret_wo.getMdl_id_fk().substring(ret_wo.getMdl_id_fk().length()-2, ret_wo.getMdl_id_fk().length());
		//第7、8码为固定00
		pallet_id = pallet_id + "00";
		//第9、10码为固定00
		pallet_id = pallet_id + "00";
		//第11、12、13、14、15码为西元后两码、月份、日期
		pallet_id = pallet_id + Util.getYearMonthDayZero(2,"N");
		String key_id = Util.getYearMonthDayZero(2,"N");
		//第16~20码为流水码
		id.setKey_id(key_id);
		id.setType("7");
		Ret_crt_no ret_crt_no = retCrtNoDao.get(id);
		if(ret_crt_no==null){
			ret_crt_no = new Ret_crt_no();
			ret_crt_no.setId(id);
		}else{
			iSerial = Integer.valueOf(ret_crt_no.getSerial_no());
		}
		iSerial++;
		pallet_id = pallet_id + Util.comInt2String(iSerial, 5);
		ret_crt_no.setSerial_no(String.valueOf(iSerial));
		retCrtNoDao.saveOrUpdate(ret_crt_no);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		outTrx.setPallet_id(pallet_id);
	}
	
	private void autoCreatStrForQR() {
		int iSerial = 0;
		String key_id = inTrx.getKey_id();
		String type = inTrx.getType();
		String secialNO = "";
		Ret_crt_noId id = new Ret_crt_noId();
		id.setKey_id(key_id);
		id.setType(type);
		Ret_crt_no ret_crt_no = retCrtNoDao.get(id);
		if(ret_crt_no==null){
			ret_crt_no = new Ret_crt_no();
			ret_crt_no.setId(id);
		}else{
			iSerial = Integer.valueOf(ret_crt_no.getSerial_no());
		}
		iSerial++;
		if(iSerial > 99999){
			outTrx.setRtn_code(E_XPCRTNO_MAX_SERIAL_NO + "");
			outTrx.setRtn_mesg("批次自动生成的最大流水码为99999！");
		}else{
			secialNO = Util.comInt2String(iSerial, 5);
			ret_crt_no.setSerial_no(secialNO);
			retCrtNoDao.saveOrUpdate(ret_crt_no);		
			outTrx.setRtn_code(RETURN_CODE_OK);
			outTrx.setRtn_mesg(RETURN_MESG_OK);
			outTrx.setSerial_no(secialNO);
		}
	}
	
	//pallet for 003
	private void autoCreatPallet003() {
		int iSerial = 0;
		String key_id = inTrx.getKey_id();
		String type = inTrx.getType();
		String secialNO = "";
		Ret_crt_noId id = new Ret_crt_noId();
		id.setKey_id(key_id);
		id.setType(type);
		Ret_crt_no ret_crt_no = retCrtNoDao.get(id);
		if(ret_crt_no==null){
			ret_crt_no = new Ret_crt_no();
			ret_crt_no.setId(id);
		}else{
			iSerial = Integer.valueOf(ret_crt_no.getSerial_no());
		}
		iSerial++;
		if(iSerial > 9999){
			outTrx.setRtn_code(E_XPCRTNO_MAX_SERIAL_NO + "");
			outTrx.setRtn_mesg("批次自动生成的最大流水码为9999！");
		}else{
			secialNO = Util.comInt2String(iSerial, 4);
			ret_crt_no.setSerial_no(secialNO);
			retCrtNoDao.saveOrUpdate(ret_crt_no);		
			outTrx.setRtn_code(RETURN_CODE_OK);
			outTrx.setRtn_mesg(RETURN_MESG_OK);
			outTrx.setSerial_no(secialNO);
		}
	}
}
